import React, { memo, useContext, useState, useEffect, useMemo, useCallback } from 'react';
import { message } from 'antd';
import { isSuccess } from '@/utils/request';
import { withRoutePage } from '@/utils/enhanceUtils';

import { hrRecheck, salaryRecheck } from '@/services/salaryManage/salaryCalculate';

import StepList from '@/pages/SalaryManage/components/StepList';
import SalaryPageWrapper from '@/pages/SalaryManage/components/SalaryPageWrapper';
import SalaryPageProvider from '@/pages/SalaryManage/components/SalaryPageWrapper/SalaryPageProvider';
import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import { possessColumn } from '@/pages/SalaryManage/SalaryCalculate/constant/salaryDetailContext';

import CheckHeader from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHeader/rechcekIndex';
import CheckBody from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckBody/index';
import OperateCell from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/OperateRender';
import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';
import {
    summaryFieldChooser,
    numberFilter,
    orFilter
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

const { getCheckButtons, reject, cancelCheck, passCheck } = hrRecheck;
const { queryTableBodyData, queryTableHeadData } = salaryRecheck;

const summaryFields = summaryFieldChooser(
    orFilter(numberFilter, col => ({
        success: col.dataIndex === 'employeeName',
        result: { [col.dataIndex]: '合计' }
    }))
);

const rowKey = 'id';

const DetailPage = memo(({ actionType }) => {
    const salaryProvider = useContext(SalaryPageProvider);
    const {
        period,
        organizationCode,
        searchModel,
        updateSignal,
        selectedRows,
        pagination,
        changeSalaryProviderParam,
        headerLoading
    } = salaryProvider;
    const [tableLoading, setTableLoading] = useState(false);
    const [stepLoading, setStepLoading] = useState(false);
    const [showHeader, setShowHeader] = useState(false);
    const [checkButtonList, setCheckButtonList] = useState([]);
    const [tableHeader, setTableHeader] = useState([]);
    const [dataSource, setDataSource] = useState({
        list: [],
        total: undefined
    });

    // 懒加载头部搜索部件
    useEffect(() => {
        if (headerLoading) {
            Promise.resolve(setShowHeader(true));
        }
    }, [headerLoading]);

    // 更新也页面数据
    const updateViewFn = useCallback(() => {
        changeSalaryProviderParam({
            updateSignal: !updateSignal
        });
    }, [changeSalaryProviderParam, updateSignal]);

    // step是否要更新
    useEffect(() => {
        let timeOut;
        if (period && organizationCode) {
            setStepLoading(true);
            timeOut = setTimeout(() => {
                setStepLoading(false);
            }, 10);
        }

        return () => {
            clearTimeout(timeOut);
        };
    }, [updateSignal, period, organizationCode]);

    // 获取可操作按钮数组
    useEffect(() => {
        const getButtonFn = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            const buttonRes = await getCheckButtons({
                year,
                month,
                organizationCode
            });

            if (isSuccess(buttonRes)) {
                setCheckButtonList(buttonRes.data || []);
            } else {
                setCheckButtonList([]);
            }
        };
        if (period && organizationCode) {
            getButtonFn();
        }
    }, [period, organizationCode, updateSignal, actionType]);

    // 获取表头头部
    useEffect(() => {
        const getHeadList = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            const headerRes = await queryTableHeadData({
                year,
                month,
                contrastType: searchModel.contrastType || '1',
                organizationCode
            });

            if (isSuccess(headerRes)) {
                setTableHeader(headerRes.data);
            } else {
                message.error(headerRes.msg);
            }
        };

        if (period && organizationCode) {
            getHeadList();
        }

        return () => {
            setTableHeader([]);
        };
    }, [period, organizationCode, searchModel.contrastType, updateSignal]);

    // 获取数据
    useEffect(() => {
        // 获取数据
        const getList = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            setTableLoading(true);
            const { current, pageSize } = pagination;
            const tableRes = await queryTableBodyData({
                organizationCode,
                year,
                month,
                nodeCode: actionType,
                ...searchModel,
                page: {
                    pageNo: current,
                    pageSize
                }
            });
            setTableLoading(false);
            if (!isSuccess(tableRes)) {
                message.error(tableRes.msg);
                return;
            }
            const { rows, total } = tableRes.data;
            setDataSource({
                list: rows,
                total
            });
        };
        if (period && organizationCode) {
            getList();
        }

        return () => {
            setDataSource({
                list: [],
                total: undefined
            });
        };
    }, [period, organizationCode, searchModel, pagination, actionType, updateSignal]);

    // 表单数据整合
    const memoDataSource = useMemo(
        () =>
            []
                .concat(dataSource.list)
                .map(item => ({ ...item.dynamicEmployeeInfo, ...item.dynamicSalaryPayrollInfo, ...item })),
        [dataSource.list]
    );

    // 表单columns整合
    const columnProcessor = useMemo(
        () =>
            new ColumnProcessor(
                possessColumn,
                CommonColumnInterceptor,
                null,
                [],
                [
                    {
                        title: '操作',
                        dataIndex: '_operate',
                        fixed: 'right',
                        width: 150,
                        align: 'center',
                        render(text, record /* , i */) {
                            return (
                                <OperateCell
                                    text={text}
                                    reject={reject}
                                    cancelCheck={cancelCheck}
                                    passCheck={passCheck}
                                    record={record}
                                    updateViewFn={updateViewFn}
                                    organizationCode={organizationCode}
                                />
                            );
                        }
                    }
                ]
            ),
        [organizationCode, updateViewFn]
    );

    return (
        <div className={salaryStyle.salaryWrapper}>
            <StepList period={period} loading={stepLoading} organizationCode={organizationCode} />
            {showHeader ? (
                <CheckHeader checkButtonList={checkButtonList} headerList={tableHeader} nodeCode={actionType} />
            ) : null}
            <BaseSettingProvider organizationCode={organizationCode}>
                <CheckBody
                    rowKey={rowKey}
                    tableHeader={tableHeader}
                    columnProcessor={columnProcessor}
                    summaryFields={summaryFields}
                    dataSource={memoDataSource}
                    changePage={changeSalaryProviderParam}
                    pagination={{
                        ...pagination,
                        total: dataSource.total
                    }}
                    searchModel={searchModel}
                    tableLoading={tableLoading}
                    selectedRows={selectedRows}
                />
            </BaseSettingProvider>
        </div>
    );
});

const HrDetail = memo(({ location }) => (
    <SalaryPageWrapper
        type="salaryRecheckDetail"
        location={location}
        lastSearch
        tabNameMap={[
            {
                name: 'hrRecheckDetail',
                title: 'HR详细',
                tabType: 1
            },
            {
                name: 'financialRecheckDetail',
                title: '财务详细',
                tabType: 2
            }
        ]}
        tabProps={{
            type: 'detail',
            overviewUrl: '/finance/salary/calculate/recheck/hrrecheck',
            detailUrl: '/finance/salary/calculate/recheck/hrrecheck/detail',
            logUrl: '/finance/salary/calculate/recheck/recheckLog'
        }}
    >
        <DetailPage actionType={3} />
    </SalaryPageWrapper>
));

export default withRoutePage(HrDetail);
